/**
 * 
 */
package com.ciukes.dynosgi.jruby;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.jruby.util.ByteList;
import org.jvyamlb.YAML;
import org.osgi.framework.Bundle;

class JRubyBundleConfig {
	private static final String KEY_INIT_SCRIPT = "init_script";
	private Map<ByteList, Object> yamlConfig;
	private final Bundle homeBundle;
	private final Collection<Bundle> searchInBundles;

	@SuppressWarnings("unchecked")
	JRubyBundleConfig(Bundle homeBundle, Collection<Bundle> searchInBundles)
			throws IOException {
		this.homeBundle = homeBundle;
		this.searchInBundles = searchInBundles;
		URL config = homeBundle.getEntry("META-INF/config.yaml");
		InputStream bundleConfig = config.openStream();
		yamlConfig = null;
		try {
			yamlConfig = (Map<ByteList, Object>) YAML.load(bundleConfig);
		} finally {
			bundleConfig.close();
		}
		if (yamlConfig == null) {
			yamlConfig = new HashMap<ByteList, Object>();
		}
	}

	public Collection<Bundle> searchInBundles() {
		return searchInBundles;
	}

	public String getInitScript() {
		ByteList value = (ByteList) yamlConfig.get(new ByteList(KEY_INIT_SCRIPT
				.getBytes()));
		return value.toString();
	}

	// TODO: JXPath to help
	// private String getProperty(String path) {
	// JXPathContext pathContext = JXPathContext.newContext(yamlConfig);
	// Object value = pathContext.getValue(path);
	// String result = null;
	// if (value instanceof ByteList) {
	// result = value.toString();
	// } else {
	// throw new IllegalArgumentException("Property is not a string type.");
	// }
	// return result;
	// }
}